package com.tencent.common;

import java.security.MessageDigest;

/**
 * User: rizenguo Date: 2014/10/23 Time: 15:43
 */
public class MD5 {
	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
			"e", "f" };

	/**
	 * 转换字节数组为16进制字串
	 * 
	 * @param b
	 *            字节数组
	 * @return 16进制字串
	 */
	public static String byteArrayToHexString(byte[] b) {
		StringBuilder resultSb = new StringBuilder();
		for (byte aB : b) {
			resultSb.append(byteToHexString(aB));
		}
		return resultSb.toString();
	}

	/**
	 * 转换byte到16进制
	 * 
	 * @param b
	 *            要转换的byte
	 * @return 16进制格式
	 */
	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	/**
	 * MD5编码
	 * 
	 * @param origin
	 *            原始字符串
	 * @return 经过MD5加密之后的结果
	 */
	public static String MD5Encode(String origin) {
		String resultString = null;
		/*String xString = "appid=wx70cbd1f125e9b16e"
				+ "&bank_type=CFT&cash_fee=1&device_info=WEB&fee_type=CNY"
				+ "&is_subscribe=Y&mch_id=1483826952&nonce_str=vas6au6jjrxr0e9nteto8x9dqjuvwg54"
				+ "&openid=oe3U7wd6e1J_ScJxgla1b-M6KIzY&out_trade_no=00000000000000000000000011001350"
				+ "&result_code=SUCCESS&return_code=SUCCESS&time_end=20170826092411&total_fee=1"
				+ "&trade_type=NATIVE&transaction_id=4002872001201708268296237013"
				+ "&key=c8d307d9624c4dd89c69fa3c9d83a5ca";*/
		try {
			resultString = origin;
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes("UTF-8")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultString;
	}
	public static void main(String[] args) {
		System.out.println(MD5.MD5Encode("appid=wx6c091aeeff8150e4&AppSecret=e0014cfce8fb656ef060219885ca7153&body=常州市-上海1天旅游包车&device_info=WEB&fee_type=CNY&mch_id=1487362632&nonce_str=9hbpdusp775il89yfhw14itz1oe6yzxz&notify_url=https://www.xiakeyueche.com/weixin/notify&out_trade_no=00000000000000000000000011001817&spbill_create_ip=182.61.34.76&total_fee=135100&trade_type=APP&key=c8d307d9624c4dd89c69fa3c9d83a5ca"));
	}
}
